<?php

// +----------------------------------------------------------------------
// | Shop-Demo for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2022~2023 Anyon <zoujingli@qq.com>
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// | 会员免费 ( https://thinkadmin.top/vip-introduce )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\data\controller\user;

use app\data\model\DataPolicyInformation;
use app\data\model\DataQiyeXinxiku as DataNewsItem;
use app\data\model\DataEnterpriseExtension;
use app\data\service\EnterpriseService;
use app\data\service\UserAdminService;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\facade\Db;
use \PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 企业信息库
 * Class Item
 * @package app\data\controller\news
 */
class QiyeXinxiku extends Controller
{
    /**
     * 企业信息
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->type = $this->get['type'] ?? 'index';
        DataNewsItem::mQuery($this->get)->layTable(function ()
        {
            $this->title = '企业信息';
        }, function (QueryHelper $query)
        {
            $query->like('qymc,tyxydm,code,phone')->dateBetween('create_at');
            $query->where(['status' => intval($this->type === 'index'), 'deleted' => 0]);
        });
    }

    /**
     * 列表数据处理
     * @param  array  $data
     */
    protected function _page_filter(array &$data)
    {
        foreach ($data as &$item) {

            if (!empty($item['qybq'])) {
                $qybq_array       = explode(',', $item['qybq']);
                $list             = Db::name("data_qiye_biaoqian")->whereIn('id', $qybq_array)->select()->toArray();
                $item['qybq_txt'] = '';
                $i                = 0;
                foreach ($list as $qybq) {
                    if ($i > 0) {
                        $item['qybq_txt'] .= ',';
                    }
                    $item['qybq_txt'] .= $qybq['name'];
                    $i++;
                }
            } else {
                $item['qybq_txt'] = '';
            }

        }

    }

    /**
     * 添加文章内容
     * @auth true
     */
    public function add()
    {
        $this->title = '添加内容';
        DataNewsItem::mForm('form');
    }

    /**
     * 编辑文章内容
     * @auth true
     */
    public function edit()
    {
        $this->title = '编辑内容';
        DataNewsItem::mForm('form');
    }

    /**
     * 表单数据处理
     * @param  array  $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if (empty($data['code'])) {

        }
        if ($this->request->isGet()) {

            $typeList = $this->getExtendedType();
            if (isset($data['id'])) {
                $data['extension'] = [];
                //查询扩展表信息  补充扩展表内容
                $extension = DataEnterpriseExtension::query()->where('enterprise_id', $data['id'])->select();
                foreach ($extension as $value) {
                    $data['extension'][DataPolicyInformation::$typeMap[$value->policy_information_type]] = $value->value;
                }
            }
            $this->enterprise_type          = $typeList['enterprise_type'] ?? [];         //企业类型
            $this->industry_classification  = $typeList['industry_classification'] ?? []; //行业分类
            $this->enterprise_scale         = $typeList['enterprise_scale'] ?? [];        //企业规模
            $this->corporate_revenue        = $typeList['corporate_revenue'] ?? [];       //企业营收
            $this->tax_bracket              = $typeList['tax_bracket'] ?? [];             //纳税等级
            $this->workers_number           = $typeList['workers_number'] ?? [];          //用工人数
            $this->develop_proportion       = $typeList['develop_proportion'] ?? [];      //研发投入占比
            $this->patent_number            = $typeList['patent_number'] ?? [];           //发明专利数量
            $this->soft_quantity            = $typeList['soft_quantity'] ?? [];           //软著数量
            $this->technical_qualifications = $typeList['technical_qualifications'] ?? [];//技术资质
            $this->industrial_chain_role    = $typeList['industrial_chain_role'] ?? [];   //产业链角色
            $this->establishment_period     = $typeList['establishment_period'] ?? [];    //成立年限
        } else {

        }
    }

    /**
     * 表单结果处理
     * @param  boolean  $state
     * @param           $data
     */
    protected function _form_result(bool $state, $data)
    {
        if ($state) {
            EnterpriseService::instance()->handleExtended($data);
            $this->success('保存成功！', 'javascript:history.back()');
        }
    }

    public function getExtendedType(): array
    {
        $type    = Db::name('data_policy_information')->whereNull('deleted')->where('status', 1)->select()->toArray();
        $data    = [
            'enterprise_type'          => [],//企业类型
            'industry_classification'  => [],//行业分类
            'enterprise_scale'         => [],//企业规模
            'corporate_revenue'        => [],//企业营收
            'tax_bracket'              => [],//纳税等级
            'workers_number'           => [],//用工人数
            'develop_proportion'       => [],//研发投入占比
            'patent_number'            => [],//发明专利数量
            'soft_quantity'            => [],//软著数量
            'technical_qualifications' => [],//技术资质
            'industrial_chain_role'    => [],//产业链角色
            'establishment_period'     => [],//成立年限
        ];
        $typeMap = DataPolicyInformation::$typeMap;
        // 遍历数据并分类
        foreach ($type as $item) {
            if (isset($typeMap[(int) $item['type']])) {
                $data[$typeMap[$item['type']]][] = $item;
            }
        }
        return $data;
    }

    /**
     * 修改文章状态
     * @auth true
     */
    public function state()
    {
        DataNewsItem::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除文章内容
     * @auth true
     */
    public function remove()
    {
        DataNewsItem::mDelete();
    }

    /**
     * 文章内容选择
     * @login true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function select()
    {
        $this->get['status'] = 1;
        $this->index();
    }


    public function getQybqList()
    {
        $biaoqian = Db::name('data_qiye_biaoqian')->where('deleted', 0)->select()->toArray();
        return_msg(200, 'success', $biaoqian);
    }


    public function import()
    {
        $file = $this->app->request->post('file');
        //        dump($file);
        //        die();

        //        if (!$file) $this->error('文件不能为空');
        $file = '.' . str_replace($this->app->request->domain(), '', $file);
        //表格字段对应
        $cellName = [
            'A' => 'qymc',  //企业名称
            'B' => 'tyxydm',//统一信用代码
            'C' => 'zczb',  //注册资本（万元）
            'D' => 'qylx',  //企业类型
            'E' => 'clrq',  //成立日期
            'F' => 'zcdz',  //注册地址
            'G' => 'qydz',  //企业地址
            'H' => 'jyfw',  //经营范围
            'I' => 'djjg',  //登记机关
            'J' => 'sbr_xm',//法人姓名
            'K' => 'phone', //法人手机号码
            'L' => 'xzbm',  //行政区域编码
            'M' => 'qybq',  //企业标签
            'N' => 'khh',   //开户行
            'O' => 'dgzhh', //对公账户号
        ];
        //加载文件
        $spreadsheet = IOFactory::load($file);

        $sheet      = $spreadsheet->getActiveSheet();               // 获取表格
        $highestRow = $sheet->getHighestRow();                      // 取得总行数
        $sheetData  = [];
        for ($row = 2; $row <= $highestRow; $row++) {          // $row表示从第几行开始读取
            foreach ($cellName as $cell => $field) {
                $value                   = $sheet->getCell($cell . $row)->getValue();
                $value                   = trim($value);
                $sheetData[$row][$field] = $value;
            }
            $sheetData[$row]['code'] = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        }
        $sheetData = array_values($sheetData);
        $count     = count($sheetData);
        //TO DO 入库
        $this->app->db->name('data_qiye_xinxiku')->data($sheetData)->strict(false)->insertAll();
        foreach ($sheetData as $item) {
            UserAdminService::handleEnterpriseUser($item);
        }
        $this->success('导入成功');
    }
}
